import styles from "./Index.module.less";
import { Button, Checkbox, Col, Form, Input, Row } from "antd";
import FontIcon from "@/components/public/fontIcon/Index";
import type { LoginForm } from "@/types/login";
import { useEffect, useState } from "react";
import { login } from "@/api/modules/login";
import { getCode } from "@/api/modules/public";
import { useSelector, useDispatch } from "react-redux";
import { setUserInfo, setRememberMe as actionSetRememberMe, setLoginForm } from "@/store/user/index";
import { store, type RootState } from "@/store/index";
import { useNavigate, useSearchParams } from "react-router-dom";
import { getRoutesByRole } from "@/api/modules/menu";
import { setDynamicMenu } from "@/store/menu";

export default function Index() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const stateRememberMe = useSelector((state: RootState) => state.user.rememberMe);
  const [searchParams] = useSearchParams();
  const redirect = searchParams.get("redirect");
  // 登录信息
  const [form] = Form.useForm<LoginForm>();

  // 记住我
  const [rememberMe, setRememberMe] = useState(stateRememberMe || false);

  const changeRememberMe = (e: any) => {
    setRememberMe(e.target.checked);
  };

  // 登录处理函数
  const handleLogin = async () => {
    try {
      let data = form.getFieldsValue(true);
      const response = await login(data);

      // 登录成功
      const { access_token, refresh_token, userInfo } = response.data;
      localStorage.setItem("token", access_token);
      localStorage.setItem("refresh_token", refresh_token);
      dispatch(setUserInfo(userInfo));
      if (rememberMe) {
        dispatch(actionSetRememberMe(true));
        dispatch(setLoginForm(data));
      }

      // 获取动态菜单
      const state = store.getState();
      let dynamicMenu = state.menu.dynamicMenu;
      const getRoutes = async () => {
        const res = await getRoutesByRole();
        dispatch(setDynamicMenu(res.data));
      };
      if (dynamicMenu.length === 0) {
        await getRoutes();
      }
      // 跳转
      navigate(redirect || "/");
    } catch (error) {
      handleeGetCode();
    }
  };

  const [codeUrl, setCodeUrl] = useState("");

  // 获取验证码
  const handleeGetCode = async () => {
    const res = await getCode();
    form.setFieldsValue({
      code: "",
      codeKey: res.data.codeKey,
    });
    setCodeUrl(res.data.url);
  };
  // 初始化时调用
  useEffect(() => {
    form.setFieldsValue({
      account: "admin",
      password: "123456",
      code: "",
      codeKey: "",
    });

    handleeGetCode();
  }, []);

  return (
    <Form
      className={styles.form}
      form={form}
      name="login"
      layout="horizontal"
      autoComplete="off"
      onFinish={handleLogin}>
      <Form.Item
        name="account"
        rules={[
          { required: true, message: "请输入账号" },
          { min: 3, max: 20, message: "账号长度应在 3 到 20 个字符之间" },
        ]}>
        <Input
          className={styles.input}
          size="large"
          placeholder="请输入账号"
          prefix={<FontIcon className={styles.icon} name="icon-user" />}
        />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          { required: true, message: "请输入密码" },
          { min: 6, max: 20, message: "密码长度应在 6 到 20 个字符之间" },
        ]}>
        <Input.Password
          className={styles.input}
          size="large"
          placeholder="请输入密码"
          prefix={<FontIcon className={styles.icon} name="icon-password" />}
        />
      </Form.Item>
      <Row gutter={8}>
        <Col span={16}>
          <Form.Item
            rules={[
              { required: true, message: "请输入图形验证码" },
              { min: 4, max: 4, message: "验证码长度为 4 个字符" },
            ]}
            name="code">
            <Input
              className={styles.input}
              size="large"
              placeholder="请输入图形验证码"
              prefix={<FontIcon className={styles.icon} name="icon-captcha" />}
            />
          </Form.Item>
        </Col>
        <Col span={8}>
          <img className={styles.code} src={codeUrl} onClick={handleeGetCode} />
        </Col>
      </Row>
      <Form.Item>
        <div className={styles.row}>
          <Checkbox checked={rememberMe} onChange={changeRememberMe}>
            记住我
          </Checkbox>
        </div>
      </Form.Item>
      <Form.Item>
        <Button type="primary" className={styles.submit} htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
}
